{% extends "zato/index.html" %}
{% load extras %}
{% block html_title %}User defined statistics{% endblock %}

{% block "extra_css" %}
    <link rel="stylesheet" type="text/css" href="/static/css/stats-user.css">
{% endblock %}

{% block "extra_js" %}

<script nonce="{{ CSP_NONCE }}">

// Maps chart / dataset IDs to Frappe charts that we display
zato_frappe_charts = {};

{% if items.charts %}
{% for chart_item in items.charts %}
    {% with datasets=chart_item.datasets %}
    {% with dataset0=datasets.0 %}
    {% with dataset_id=dataset0|get_item:"id" %}
    zato_frappe_charts["{{ dataset_id }}"] = [];
    {% endwith %}
    {% endwith %}
    {% endwith %}
{% endfor %}
{% endif %}

</script>

<script nonce="{{ CSP_NONCE }}" type="text/javascript" src="/static/js/common.js"></script>
<script nonce="{{ CSP_NONCE }}" type="text/javascript" src="/static/frappe-charts/frappe-charts.min.iife.js"></script>

<script nonce="{{ CSP_NONCE }}">

    $(document).ready(function() {

        var charts_form   = $("#charts-form");
        var charts_action = $("#charts-action");
        var compare_stats_button = $('#submit-CompareStats')

        var maybe_toggle_compare = function() {
            var checked = $('.row-checkbox:checkbox:checked');
            var should_enable = checked.length >= 1;
            if(should_enable) {
                compare_stats_button.prop("disabled", false);
            }
            else {
                compare_stats_button.prop("disabled", true);
            }
        }

        $('#check-all-rows').click(function() {
            $('.row-checkbox').prop('checked', this.checked);

            if(this.checked) {
                maybe_toggle_compare();
            }
            else {
                compare_stats_button.prop("disabled", true);
            }
        });

        $(charts_form).click(function(e) {
            var elem = $(document.activeElement);
            var action = elem.attr("data-action")
            charts_action.attr("value", action)
            return true;
        });

        $(".row-checkbox").click(function(e) {
            maybe_toggle_compare();
        });

        {% if items.charts %}

        var on_success = function(data) {

            // This is needed to make legends wider
            const empty_dataset = {name: "", type: "line", values: []};

            var charts_data = data.charts;
            if(!charts_data) {
                return;
            }

            {% if action == "CompareStats" %}
            // Each chart will contain the same metadata
            var chart0 = charts_data[0];

            var frappe_data = {
                "labels": chart0.labels,
                "yMarkers": [{
                    "label": chart0.label_y,
                    "value": chart0.max_y,
                    "options": {"labelPos": "left"}
                }],
                "datasets": [],
            };

            for (chart_elem of charts_data) {
                var frappe_dataset = {
                    "name":  chart_elem.datasets[0].name_short,
                    "type":  "line",
                    "values": chart_elem.datasets[0].values,
                }
                frappe_data.datasets.push(frappe_dataset);
                frappe_data.datasets.push(empty_dataset);
            }
            frappe_chart0.update(frappe_data);

            {% else %}

            // Go through each chart that we received ..
            for(const incoming_chart of charts_data) {

                // .. enter each dataset of each chart ..
                for(const incoming_dataset of incoming_chart.datasets) {

                    // Shortcut
                    const incoming_dataset_id = incoming_dataset.id;

                    // Among charts already displayed on the page, find those that contain
                    // a dataset that we are iterating over above
                    var page_charts = zato_frappe_charts[incoming_dataset_id];

                    // Go over each already existing matching chart
                    for(var page_chart of page_charts) {

                        // Prepare basic data for a set of new data for that chart

                        var frappe_data = {
                            "labels": incoming_chart.labels,
                            "yMarkers": [{
                                "label": incoming_chart.label_y,
                                "value": incoming_chart.max_y,
                                "options": {"labelPos": "left"}
                            }],
                            "datasets": [],
                        };

                        var frappe_dataset = {
                            "name": incoming_dataset.name_short,
                            "type": "line",
                            "values": incoming_dataset.values,
                        }

                        // .. add current dataset to the chart along with the empty one needed to make the legend longer
                        frappe_data.datasets.push(frappe_dataset);
                        frappe_data.datasets.push(empty_dataset);

                        // .. finally, update the chart with the new data.
                        page_chart.update(frappe_data);
                    }
                }
            }
            {% endif %}
        }

        var update_chart = function() {

            var item_id_list = [];
            var item_id_elems = $(":input[name='item-id']").get();

            for (item_id_elem of item_id_elems) {
                item_id_list.push(item_id_elem.value);
            }

            if(!item_id_list) {
                return;
            }

            var request = {
                "id": item_id_list,
            }
            request = JSON.stringify(request);

            $.ajax({
                "contentType": "application/json; charset=utf-8",
                "dataType": "json",
                "type": "POST",
                "url": "./get-updates/",
                "data": request,
                "headers": {"X-CSRFToken": "{{ csrf_token }}"},
                success: function(response) {
                    on_success(response);
                },
                failure: function(response) {
                    console.log("Failed to invoke /update " + response.text)
                }
            });
        }

        $('#update-stats').click(function() {
            update_chart();
        });

        setInterval(update_chart, 3000);

        {% endif %}
    })

</script>

{% endblock %}

{% block "content" %}
<h2 class="zato">User defined statistics</h2>

{% if not zato_clusters %} {% include "zato/no-clusters.html" %} {% else %}

{% if cluster_id %}

<div id="markup" style="width: 90% !important;">

    <div style="text-align: center !important;">
    <br/>

    <form novalidate id="charts-form" action=".">
    <table id="data-table" style="width:80%; margin: auto">

        {% if action != "BrowseStats" %}
        <thead>
            <tr>
                <td colspan="9999">

                {% if items.charts %}
                <table class="charts-display-table" style="width:100%;">

                {% if action == "DisplayStats" %}
                {% for chart_item in items.charts %}
                    <tr>

                    {% with chart_idx=forloop.counter0 %}

                    <td style="width:76%; border-bottom: 1px solid #ccc; vertical-align:middle; padding-right:0px; margin-right:0px; ">
                        <div id="chart{{ forloop.counter0 }}" class="charts-div"></div>
                    </td>
                    <td class="desc" style="border-bottom: 1px solid #ccc; vertical-align: top; padding-top: 3%; color:#666;">
                        <table style="width: 100%;">
                            {% for column in columns %}
                            {% with column_idx=forloop.counter0 %}
                            {% with row=items.rows|get_item:chart_idx %}
                            {% with cell=row.cells|get_item:column_idx %}
                            <tr>
                                <td style="vertical-align:middle; border: 1px dotted #ccc;">{{ column.data }}</td>
                                <td style="vertical-align:middle; border: 1px dotted #ccc; ; font-size:{{ cell.size }}em">
                                    {% if cell.data %}
                                    {% if cell.datatype == "link" %}
                                        <a href="?{{ form_item_id_prefix }}{{ row.id }}=on&amp;action=DisplayStats">{{ cell.data }}</a>
                                    {% elif cell.datatype == "email" %}
                                        <span {% if cell.color %}style="color:{{ cell.color }}{% endif %}">⯀</span>
                                        <a href="?{{ column.key }}={{ cell.data }}&amp;action={{ action }}">{{ cell.data }}</a>
                                    {% else %}
                                        {{ cell.data }}
                                    {% endif %}
                                {% else %}
                                    {{ cell|default:"---" }}
                                {% endif %}
                                </td>
                            </tr>
                            {% endwith %}
                            {% endwith %}
                            {% endwith %}
                            {% endfor %}
                        </table>
                    </td>

                    <script nonce="{{ CSP_NONCE }}">

                        // ////////////////////////////////////////////////////////////////////////////////////////

                        const data{{ chart_idx }} = {

                            labels: {{ chart_item.labels }},

                            yMarkers: [{
                                label: "{{ chart_item.label_y }}",
                                value: {{ chart_item.max_y }},
                                options: { labelPos: 'left' }
                                }],

                            datasets: [
                                {% for dataset in chart_item.datasets %}
                                {
                                name: "{{ dataset.name }}", type: "line",
                                values: {{ dataset.values }}
                                },
                                {% endfor %}

                                {name: "", type: "line", values: []}, {% comment %} This is empty on purpose, to make the legend with the label longer {% endcomment %}
                            ]

                            }

                            const frappe_chart{{ chart_idx }} = new frappe.Chart("#chart{{ chart_idx }}", {
                                title: "{{ chart_item.name }}",
                                data: data{{ chart_idx }},
                                type: 'line',
                                {% with chart_item_colors=chart_item.colors|safe %}
                                colors: {{ chart_item_colors }}.concat({{ chart_item_colors }}),
                                {% endwith %}
                                xvaluesOverPoints: 1,
                                isNavigable: true,

                            axisOptions: {
                                xAxisMode: 'span',
                                yAxisMode: 'span',
                                xIsSeries: true
                            },
                            barOptions: {
                                spaceRatio: 2
                            },
                            lineOptions: {
                                dotSize: 2,
                                spline: 0,
                                hideDots: false,
                            },
                            tooltipOptions: {
                                formatTooltipX: d => d + ' min.',
                                formatTooltipY: d => '',
                            }
                            });

                            frappe_chart{{ chart_idx }}.zato_options = {
                                "id": [
                                {% for dataset in chart_item.datasets %}
                                    "{{ dataset.id }}",
                                {% endfor %}
                                ]
                            };

                            {% for dataset in chart_item.datasets %}
                                zato_frappe_charts["{{ dataset.id }}"].push(frappe_chart{{ chart_idx }});
                            {% endfor %}

                        </script>

                    </tr>
                    {% endwith %}

                {% endfor %}
                {% elif action == "CompareStats" %}

                {% with chart_item=items.charts.0 %}
                {% with chart_max_x=chart_item.max_x chart_max_y=chart_item.max_y chart_label_y=chart_item.label_y %}

                    <tr>
                        <td style="width:100%; border-bottom: 1px solid #ccc; style="vertical-align:middle; ">
                            <div id="chart0" class="charts-div"></div>
                            <script nonce="{{ CSP_NONCE }}">
                            const data = {

                                labels: {{ chart_item.labels }},

                                yMarkers: [{
                                    label: "{{ chart_item.label_y }}",
                                    value: {{ chart_max_y }},
                                    options: { labelPos: 'left' }
                                    }
                                ],

                                datasets: [

                                {% for chart_item in items.charts %}
                                    {% for dataset in chart_item.datasets %}
                                    {
                                    name: "{{ dataset.name_short }}", type: "line",
                                    values: {{ dataset.values }}
                                    },
                                    {% endfor %}
                                    {name: "", type: "line", values: []}, {% comment %} This is empty on purpose, to make the legend with the label longer {% endcomment %}
                                {% endfor %}
                            ]

                            }

                            var frappe_chart0 = new frappe.Chart("#chart0", {
                                title: "Comparison",
                                data: data,
                                type: 'line',
                                colors: [
                                    {% for chart_item in items.charts %}
                                        '{{ chart_item.colors.0 }}',
                                        '{{ chart_item.colors.0 }}',
                                    {% endfor %}
                                ],
                                xvaluesOverPoints: 1,
                                isNavigable: true,

                                axisOptions: {
                                    xAxisMode: 'span',
                                    yAxisMode: 'span',
                                    xIsSeries: true
                                },
                                barOptions: {
                                    spaceRatio: 2
                                },
                                lineOptions: {
                                    dotSize: 2,
                                    spline: 0,
                                    hideDots: false,
                                },
                                tooltipOptions: {
                                    formatTooltipX: d => d + ' min.',
                                    formatTooltipY: d => '',
                                }
                            });

                            frappe_chart0.zato_options = {
                                "id": [
                                {% for chart_item in items.charts %}
                                {% for dataset in chart_item.datasets %}
                                    "{{ dataset.id }}",
                                {% endfor %}
                                {% endfor %}
                                ]
                            };

                            {% for chart_item in items.charts %}
                            {% for dataset in chart_item.datasets %}
                                zato_frappe_charts["{{ dataset.id }}"].push(frappe_chart0);
                            {% endfor %}
                            {% endfor %}

                            </script>
                        </td>
                    </tr>

                {% endwith %}
                {% endwith %}

                {% endif %}
                </table>

                {% endif %}

                </td>
            </tr>
        </thead>
        {% endif %}

        <thead>
            <tr class='ignore'>
                <td colspan="3" style="text-align: left;">
                    ← <a href="?cluster={{ cluster_id }}">Back to main page </a>
                </td>
                <td colspan="5" style="text-align: right;">
                        {% for container in dicts.containers %}
                        {% with req_value=req.GET|get_item:container.name %}
                        <select name={{ container.name }}>
                            <option value="">---</option>

                            {% if container.datatype == "email" %}
                                {% for key, values in container.elems.items %}

                                    <option value="{{ key }}" class="group"
                                        {% if key|endswith:req_value %}
                                            selected="selected"
                                        {% endif %}
                                    >◾️ {{ key|upper }}</option>
                                    {% for value in values %}
                                        <option value="{{ value.key }}" class="value"
                                            {% if req_value == value.key %}
                                                selected="selected"
                                            {% endif %}
                                        >{{ value.key }}</option>
                                    {% endfor %}
                                {% endfor %}
                            {% else %}
                                {% for elem in container.elems %}
                                    <option value="{{ elem.key.id }}" class="value"
                                        {% if req_value == elem.key.id %}
                                            selected="selected"
                                        {% endif %}
                                    >{{ elem.key.name }}</option>
                                {% endfor %}
                            {% endif %}

                        </select>
                        {% endwith %}
                        {% endfor %}

                        <input type="hidden" id="charts-action" name="action" value="{{ action }}"/>

                        {% comment %}
                        <input id="update-stats" type="button" value="Update" />
                        {% endcomment %}

                        <input id="submit-BrowseStats"  type="submit" data-action="BrowseStats"  value="List" />
                        <input id="submit-DisplayStats" type="submit" data-action="DisplayStats" value="Display" />
                        <input id="submit-CompareStats" {% if id_checked|length < 2 %}disabled="true"{% endif %}  type="submit" data-action="CompareStats" value="Compare" />

                </td>
            </tr>
        </thead>
        <thead>
            <tr class='ignore'>
                <th>
                    {% if items %}
                        <input type="checkbox" id="check-all-rows" />
                    {% endif %}
                </th>
                <th>&nbsp;</th>
                {% for column in columns %}
                    <th style="text-align: {{ column.align }}"><a href="#">{{ column.data }}</a></th>
                {% endfor %}
        </thead>

        <tbody>
            {% if items.rows %}
                {% for item in items.rows %}
                <input type="hidden" name="item-id" value="{{ item.id }}" />
                <tr class="{% cycle 'odd' 'even' %}" id='tr_{{ item.id }}'>
                    <td><input type="checkbox" class="row-checkbox" name="{{ form_item_id_prefix }}{{ item.id }}" {% if item.id in id_checked %}checked="checked"{% endif %} /></td>
                    <td class='numbering' style="width:10px">&nbsp;</td>
                        {% for cell in item.cells %}
                            {% with cell_idx=cell.idx %}
                            {% with cell_column=columns|get_item:cell_idx %}
                            <td style="text-align: {{ cell.align|default:'left' }}; font-size:{{ cell.size }}em">
                                {% if cell.data %}
                                    {% if cell.datatype == "link" %}
                                        <a href="?{{ form_item_id_prefix }}{{ item.id }}=on&amp;action=DisplayStats">{{ cell.data }}</a>
                                    {% elif cell.datatype == "email" %}
                                        <span{% if cell.color %} style="color:{{ cell.color }}"{% endif %}>⯀</span>
                                        <a href="?{{ cell_column.key }}={{ cell.data }}&amp;action={{ action }}">{{ cell.data }}</a>
                                    {% else %}
                                        {{ cell.data }}
                                    {% endif %}
                                {% else %}
                                    {{ cell|default:"---" }}
                                {% endif %}
                            </td>
                            {% endwith %}
                            {% endwith %}
                        {% endfor %}
                    </tr>
                {% endfor %}
            {% else %}
                <tr class='ignore'>
                    <td colspan='4'>No results</td>
                </tr>
            {% endif %}

        </tbody>
    </table>
</form>

<br/>
<br/>


    </div>
</div>

{% endif %} {% comment %}cluster_id{% endcomment %}

{% endif %}{% comment %}not zato_clusters{% endcomment %} {% endblock %}
